package com.mo.security.controller;

import com.mo.security.common.Result;
import com.mo.security.domain.User;
import com.mo.security.domain.UserDetailsImpl;
import com.mo.security.utils.JWTUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Objects;

@RestController
@RequestMapping("login")
public class LoginController {
    @Resource
    JWTUtils jwtUtils;

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping
    public Result login(@RequestBody User user) {
        // 在这里得到 UserDetailsServiceImpl 查询到的用户信息，并且已经通过密码校验
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();

        if (Objects.isNull(loginUser)) {
            return Result.error("用户名或密码有误", HttpServletResponse.SC_BAD_REQUEST);
        }

        // token 可以存很多信息，看个人选择
        String userId = loginUser.getUser().getId().toString();
        String username = loginUser.getUser().getUsername();
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("loginTime", System.currentTimeMillis());

        String token = jwtUtils.generateToken(userId, claims);

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userId", userId);
        map.put("username", username);
        Object[] authArray = loginUser.getUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).toArray();
        map.put("authorities", authArray);

        return Result.success("登录成功", map);
    }
}
